﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Marbles.Core.Web.Syndication;
using Marbles.Core.Web.Syndication.Atom;
using Marbles.Core.Web.Syndication.RSS;
using Marbles.Core.Web.Resources;

namespace Marbles.Core.Web.Controls.WebParts
{
    [ToolboxData("<{0}:FeedViewer runat=server></{0}:FeedViewer>")]
    public class FeedViewer : WebPart
    {
        [Category("Appearance")]
        public string FeedUrl
        {
            get
            {
                String s = (String)ViewState["FeedUrl"];
                return ((s == null) ? String.Empty : s);
            }
            set
            {
                ViewState["FeedUrl"] = value;
            }
        }

        [Category("Appearance")]
        public int CellPadding
        {
            get
            {
                object i = ViewState["CellPadding"];
                if (i == null) { return 0; }
                return Convert.ToInt32(i);
            }
            set
            {
                ViewState["CellPadding"] = value;
            }
        }

        [Category("Appearance")]
        public int CellSpacing
        {
            get
            {
                object i = ViewState["CellSpacing"];
                if (i == null) { return 0; }
                return Convert.ToInt32(i);
            }
            set
            {
                ViewState["CellSpacing"] = value;
            }
        }

        [Category("Appearance")]
        public bool ShowFeedTitle
        {
            get
            {
                object obj = ViewState["ShowFeedTitle"];
                if (obj == null) { return true; }
                return Convert.ToBoolean(obj);
            }
            set { ViewState["ShowFeedTitle"] = value; }
        }

        [Category("Appearance")]
        public bool ShowFeedIcon
        {
            get
            {
                object obj = ViewState["ShowFeedIcon"];
                if (obj == null) { return true; }
                return Convert.ToBoolean(obj);
            }
            set { ViewState["ShowFeedIcon"] = value; }
        }

        [Category("Appearance")]
        public TableItemStyle LinkStyle
        {
            get { return this._linkstyle; }
        }

        [Category("Appearance")]
        public TableItemStyle HeaderStyle
        {
            get { return this._headerstyle; }
        }

        [Category("Appearance")]
        public TableItemStyle ItemStyle
        {
            get { return this._itemstyle; }
        }

        [Category("Appearance")]
        public TableItemStyle TitleStyle
        {
            get { return this._titlestyle; }
        }


        private TableItemStyle _linkstyle = new TableItemStyle();
        private TableItemStyle _headerstyle = new TableItemStyle();
        private TableItemStyle _titlestyle = new TableItemStyle();
        private TableItemStyle _itemstyle = new TableItemStyle();

        protected override void CreateChildControls()
        {
            Panel pnl = this.CreatePanel();
            Table tbl = this.CreateTable();

            FeedReader rdr = new FeedReader(new Uri(this.FeedUrl));
            IFeed feed = rdr.Read();

            if (feed != null)
            {
                if (ShowFeedTitle) { this.Controls.Add(GetFeedTitle(feed)); }

                switch (feed.FeedType)
                {
                    case FeedType.RSS: RenderFeed((RSSFeed)feed, tbl); break;
                    case FeedType.Atom: RenderFeed((AtomFeed)feed, tbl); break;

                }
            }

            pnl.Controls.Add(tbl);

            this.Controls.Add(pnl);
        }

        private Panel GetFeedTitle(IFeed Feed)
        {
            Panel pnl = new Panel();
            Table tbl = new Table();
            TableRow row = new TableRow();
            TableCell celltitle = new TableCell();

            pnl.Width = Width;
            tbl.ID = "ChildTitleTable";
            tbl.Width = new Unit(100, UnitType.Percentage);
            tbl.CellSpacing = 0;
            tbl.CellPadding = 0;
            pnl.ID = "ChildTitle";
            pnl.ApplyStyle(this._titlestyle);
            pnl.ToolTip = Feed.Title;
            celltitle.Text = Feed.Title;
            celltitle.HorizontalAlign = HorizontalAlign.Left;
            row.Cells.Add(celltitle);

            if (this.ShowFeedIcon)
            {
                TableCell cellicon = new TableCell();
                HyperLink link = new HyperLink();
                link.Target = "_new";
                WebResources imgRes = new WebResources();
                cellicon.HorizontalAlign = HorizontalAlign.Right;
                link.NavigateUrl = this.FeedUrl;
                link.ImageUrl = imgRes.FeedIconResourceUrl;
                link.Width = new Unit(16, UnitType.Pixel);
                link.Height = new Unit(16, UnitType.Pixel);
                link.ToolTip = "View Feed";
                cellicon.Controls.Add(link);
                row.Cells.Add(cellicon);
            }

            tbl.Controls.Add(row);
            pnl.Controls.Add(tbl);
            return pnl;
        }

        private Table CreateTable()
        {
            Table tbl = new Table();
            tbl.ID = "ChildTable";
            tbl.CellPadding = this.CellPadding;
            tbl.CellSpacing = this.CellSpacing;
            tbl.GridLines = GridLines.None;
            return tbl;
        }

        private Panel CreatePanel()
        {
            Panel pnl = new Panel();
            pnl.ID = "ChildPanel";
            pnl.Width = this.Width;

            if (ShowFeedTitle)
            {
                pnl.Height = new Unit(this.Height.Value - this.TitleStyle.Height.Value, this.Height.Type);
            }
            else
            {
                pnl.Height = this.Height;
            }
            pnl.ScrollBars = this.ScrollBars;
            pnl.ForeColor = this.ForeColor;
            pnl.BackColor = this.BackColor;
            return pnl;
        }

        private void RenderFeed(AtomFeed Feed, Table Table)
        {
            foreach (AtomItem item in Feed.Items)
            {
                Table.Rows.Add(CreateHeadlineRow(item));
                Table.Rows.Add(CreateItemRow(item));
            }
        }

        private void RenderFeed(RSSFeed Feed, Table Table)
        {
            foreach (RSSItem item in Feed.Items)
            {
                Table.Rows.Add(CreateHeadlineRow(item));
                Table.Rows.Add(CreateItemRow(item));
            }
        }

        private TableRow CreateHeadlineRow(IFeedItem Item)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            row.ApplyStyle(this._headerstyle);
            if (Item.Link == null)
            {
                cell.Text = Item.Title;
            }
            else
            {
                HyperLink link = new HyperLink();
                link.Target = "_new";
                link.ApplyStyle(this._linkstyle);
                link.Text = Item.Title;
                link.ToolTip = Item.Title;
                link.NavigateUrl = Item.Link.OriginalString;
                cell.Controls.Add(link);
            }
            row.Cells.Add(cell);
            return row;
        }

        private TableRow CreateItemRow(IFeedItem Item)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            row.ApplyStyle(this._itemstyle);
            cell.Text = string.Format("{0}<br /><font size=-1>{1} {2}</font>", Item.Description, Item.PublishDate.ToLongDateString(), Item.PublishDate.ToShortTimeString());
            row.Cells.Add(cell);
            return row;
        }
    }
}
